﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
namespace Data
{
   public class HoaDonRepository
    {
       public static int GetCurrentID()
       {
           NhaSachEntities context = new NhaSachEntities();
           Nullable<int> id = context.GetCurrentID("HoaDon").SingleOrDefault();
           return (int)id;
       }
       public static void InsertHoaDon(List<ChiTietHoaDonDTO> list, HoaDonDTO hoaDon)
       {
           NhaSachEntities context = new NhaSachEntities();
           HoaDon hd = new HoaDon();
           hd.NgayLap=hoaDon.NgayLap;
           hd.TinhTrang=1;
           hd.TongTien = hoaDon.TongTien;
           var khachHang = (from kh in context.KhachHangList
                            where kh.MaKhachHang == hoaDon.MaKhachHang
                            select kh).FirstOrDefault();
           khachHang.TienNo += hoaDon.TongTien;
           hd.KhachHang = khachHang;


           foreach (ChiTietHoaDonDTO ct in list)
           {
               ChiTietHoaDon cthd = new ChiTietHoaDon();
               cthd.MaSach = ct.MaSach;
               cthd.SoLuongBan=ct.SoLuongBan;
               cthd.DonGiaBan = ct.DonGiaBan;
               var sach = (from s in context.SachList
                           where s.MaSach == ct.MaSach
                           select s).FirstOrDefault();
               sach.SoLuong -= ct.SoLuongBan;
               hd.ChiTietHoaDons.Add(cthd);
           }
           context.AddToHoaDonList(hd);
           context.SaveChanges();

       }

       public static bool Exists(int maHoaDon)
       {
           NhaSachEntities context = new NhaSachEntities();
           var q = (from hd in context.HoaDonList
                    where hd.MaHoaDon == maHoaDon
                    select hd).FirstOrDefault();
           if (q == null)
               return false;
           return true;
       }
    }
}
